$(function () {
	// 定时器
	var timer = "";
	var rTimer;
	var dataCount=0;
	var page = 1;
	var htmlStr = "";
	var navHStr = "";
	var favaCounts = [];
	var isRemind = false;
	// 当页面滚动式，出现上滑到顶部和底部的按钮
	// 并且通知消息框消失
	var totalHeight;

	var backData = false;
	var sT =0;
	
	function formatDate(time){
		time = new Date(time);
		var am = "";
		var y = time.getFullYear();		
		var M = time.getMonth()+1;
		var d = time.getDate();
		var h = time.getHours();
		var m = time.getMinutes();
		M = M<10 ? "0"+M : M;
		d = d<10 ? "0"+d : d;
		h = h<10 ? "0"+h : h;
		m = m<10 ? "0"+m : m;
		if(h<=12){
			am = "上午";
		}else{
			am = "下午"
		}
		return y+"-"+M+"-"+d+" "+am+" "+h+":"+m;
	}
	
	$("#data-content").on("scroll", function () {
		//			alert(1)
//		$(this).data("scroll",true);
		var s = 1;
		 sT = $("#data-content").scrollTop();
		var height = $("#data-content").height();
		var total = sT + height;
		clearTimeout(rTimer);
		timeOut();
		rTimer = setTimeout(function () {
			$("#searchDiv ul").slideUp();
		}, 4000)
		if (sT) {
			clearTimeout(timer);
			$(".shortcutBtn").fadeIn();
			timer = setTimeout(function () {
				$(".shortcutBtn").fadeOut();
			}, 2000);
		}
//		console.log(totalHeight);
//		console.log(total);

		if (total >= totalHeight - 10 - 44 && !backData) {
			//				sendFCs();
			$(".loading").css({
				backgroundImage: "url(../images/loading_010.gif)",
				backgroundRepeat: "no-repeat",
				backgroundPosition: "50% 0"
			}).find("div").hide();
			page = page + 1;
			console.log(page + "page");
			backData = true;
			$.ajax({
				type: "get",
				url: "/themeList",
				async: true,
				data: {
					page: page
				}
			}).done(function (resData) {
				console.log(resData.total + "total");
				// console.log(page + "page");
					console.log(resData);
				if (resData.total > page) {
					
					htmlStr = template("mainTemplate", resData);
					$("#data-content").append(htmlStr);
					var htmls= [];
					for(var i=0;i<resData.main.length;i++){
						htmls.push(resData.main[i].content)
					}
					for(var i=0;i<htmls.length;i++){
						$(".mc").eq(dataCount+i).html(htmls[i]);
					}
					
					
					$(".loading").appendTo("#data-content");
					dataCount = dataCount+ resData.main.length;
					totalHeight = $("#data-content")[0].scrollHeight;
					$(".dataCount").text(dataCount);
					
					$(".pTime").each(function(index){
						if(index > dataCount -1){
							var text = formatDate($(this).text());
							$(this).text(text);
							}
					})
					$(".loading").css("background-image", "").find("div").show().find(".iconM").show().next().text("上拉加载");
					backData = false;
				} else {
//					alert(1);
					$(".loading").css("background-image","url( )").find("div").show().find("span").eq(0).hide().next().text("没有更多的数据...");
				}
			}).fail(function (jqXHR, status, error) {
				console.log(error);
				$(".loading").css("background-image", "").find("div").show().html("<p><span class='glyphicon glyphicon-remove'></span>&nbsp;加载失败</p>");

			})
		}
	});

	//			$("#data-content ul").on("click",function(event){
	//				event.stopImmediatePropagation();
	//				timeout();
	//				clearTimeout(rTimer);
	//			})
	// 回到顶部按钮事件 
	$("#backTop").click(function (event) {
		$("#data-content").animate({
			scrollTop: 0
		}, 500);

	});
	// 回到底部按钮事件
	$("#backBottom").click(function () {
		var vh = $("#data-content")[0].scrollHeight-$("#data-content").height()-20;
		$("#data-content").animate({
			scrollTop: vh
		}, 500);
	});
	// 顶部通知栏出现
//	console.log($.cookie("wcID"));


	// timeOut 让顶部消息栏消失
	function timeOut() {
		$("#remind").stop().slideUp();

	};
	// 5s 后 顶部消息栏消失
	function remindUp() {
		rTimer = setTimeout(timeOut, 5000);
	}
	remindUp();
	// 点击顶部的消息按钮，出现或消失 顶部消息栏
	$(".titleMessage").on("click", function () {
//		alert(1);
		if($.cookie("wcID")){
			$("#remind").stop().slideToggle();
			remindUp();
		}	
	});
	// 
	setTimeout(function () {
		$("#nav").fadeIn(1000);
	}, 2000)
	// 调节底部 分页栏位置 和顶部通知栏的位置
	function navPosition() {
		var wx = $(window).width() / 2 - 59;
		var bx = $(window).width() / 2 + 50;
		$("#nav").css("left", wx);
		$(".dataCount").css("left", bx);
	}
	navPosition();
	$(window).resize(function () {
		navPosition();
		totalHeight = $("#data-content")[0].scrollHeight;
	});

	var index = 0;
	// 侧边栏的一级列表事件
	$(".navMenu").on("click", ".listOnce", function () {
		if (!$(this).data("open")) {
			$(this).find("span").removeClass("glyphicon-triangle-right").addClass(" glyphicon-triangle-bottom").end().next().slideDown();
			$(this).data("open", true);
		} else {
			$(this).find("span").removeClass(" glyphicon-triangle-bottom").addClass("glyphicon-triangle-right ").end().next().slideUp();
			$(this).data("open", false);
		}
	});
	// 点击汉堡包菜单 弹出侧边栏
	$(".menuButton").click(function () {
		clearTimeout(rTimer);
		timeOut();
		$("body").css("overflow", "hidden");
		var random = Math.floor(Math.random() * 5);
		var colors = ["lightblue", "lightcoral", "lightgrey", "lightpink", "lightgoldenrodyellow"];
		$(".guard").slideDown();
		$(".navMenu").css("background-color", colors[random]).show(1000);
//			clearTimeout(timer);
			$(".shortcutBtn").css("z-index",-1);
//			$(".shortcutBtn").fadeIn();
//			timer = setTimeout(function () {
//				$(".shortcutBtn").fadeOut();
//			}, 2000);
	});
	// 点击侧边栏关闭按钮 关闭侧边栏
	function closeLNav() {
		$(".guard").slideUp();
		$(".navMenu").hide(1000);
		$("body").css("overflow", "scroll");
		$(".shortcutBtn").css("z-index",1000);
		
	}
	$(".closeLeftMenu").click(function () {
		closeLNav();
	})
	//



	/*************请求*************/
	
	$.ajax({
		type: "get",
		url: "/themeList",
		async: true,
	}).done(function (resdata, status, jqXHR) {
		console.log(resdata)
		if (status == "success") {
			// 顶部通知栏最新数据
			var data = resdata;
			dataCount = dataCount+ data.main.length;
			console.log(resdata);
			
			formatDate(data.main.update_time);
			$("#newReply").text(data.newReply);
			
			
			if(data.newReply){
				$(".newReply").text(data.newReply).next().show().parents("li").addClass("active");
				
			}
			
			if(data.newSub){
				$("#newSubscribe").text(data.newSub).next().show().parents("li").addClass("active");
			}
			
			// $("#newHistory").text(data.newHistory);
			$("#newSubscribe").text(data.newSub);
//			$(".title").text(data.title);
			htmlStr = template("mainTemplate", data);

//			$(".title").text(data.title);
			$("#data-content").html(htmlStr).slideDown();
//			$(".mc").eq(1).html("<img src='../../bin/public/uploads-min/photo-1490193172158.jpg'/>dwadaw")
//			console.log($(".pTime").text());
			var htmls = [];
			for(var i=0;i<data.main.length;i++){
				htmls.push(data.main[i].content);
			}
//			console.log(htmls);			
			$(".message").each(function(index){
				$(this).find(".mc").html(htmls[index]);
			});
			$(".pTime").each(function(){
					var text = formatDate($(this).text());
					$(this).text(text);
				})
			var loading = "<footer class='loading'><div><span class='glyphicon glyphicon-cloud-upload iconM'></span><span class='loadText'>上拉加载</span></div></footer>"
			$("#data-content").append(loading);
			navHStr = template("leftNavTemplate", data);
			$("#navContainer").html(navHStr);
			totalHeight = $("#data-content")[0].scrollHeight;
			dataCount = resdata.main.length;
			$(".dataCount").text(dataCount);
			$("#data-content").animate({
			scrollTop: 0
			}, 500);
			 console.log(totalHeight);
			 isRemind = sessionStorage.getItem("noRemind");
			 console.log(isRemind);
			 console.log($.cookie("wcID"));
			if ($.cookie("wcID")&&isRemind) {
				
				
					$("#remind").slideDown();
					console.log(1);
						$(".noRemind").text("点击不再提醒");
					remindUp();
			}
				
			}else{
					console.log(2)
//				$(".titleMessage").off("click");
				$(".noRemind").text("点击提醒")
			
			 
		}
	}).fail(function (jqXHR, status, error) {
		console.log(error);
	});
	

	
	$(".noRemind").on("click",function(){
//		$("#remind").slideUp();
			console.log(isRemind);
		if(!isRemind){
			$(this).text("点击提醒")
			sessionStorage.setItem("noRemind",1);
			isRemind = true;
			console.log(sessionStorage.getItem("noRemind"))
		}else{
			$(this).text("点击不再提醒")
			sessionStorage.setItem("noRemind","");	
			isRemind = false;
			console.log(sessionStorage.getItem("noRemind"))
			
		}
		$("#remind").slideUp();
	})


	$("#data-content").on("click", ".moveTheme", function () {
		// 修改本地存储浏览历史
		var array;
		var historyarray = JSON.parse(window.localStorage.getItem("history_list"));

		if (historyarray == null) {
			array = [];
		} else {
			array = historyarray;
			console.log(array);
		}
		var theme_id = $(this).data('id');
		for (var i = 0; i < array.length; i++) {
			if (array[i] == theme_id) {
				array.splice(i, 1);
			}
		}
		console.log(theme_id);
		array.push(theme_id);
		window.localStorage.setItem('history_list', JSON.stringify(array));
		console.log(historyarray);
		location.href = "/theme.html?id=" + theme_id;
	});

	$("#searchSection").on("input", function () {
		var searchStr = $(this).val();
		if (!searchStr) {
			$("#navContainer").html(navHStr);
		} else {
			$(".titleOnce").each(function (index, value) {
				if ($(this).text().includes(searchStr)) {
					var htmlStr = "<li class='list-group-item listOnce'>";
					htmlStr += $(this).parent().html();
					htmlStr += "</li><ul class='list-group listSecond'>";
					htmlStr += $(this).parent().next().html();
					htmlStr += "</ul>";
					$("#navContainer").html(htmlStr);
				}
			});
		}
	});

	$(".navMenu").on("click", ".theme", function () {
		closeLNav();
		var data = {
			forum_id: $(this).data('id')
		};
		$(".title").text($(this).text());
		$.get("/themeList", data, function (resData) {
			console.log(resData);
			var data = resData;
			$("#newReply").text(data.newReply);
			$("#newSubscribe").text(data.newSub);
//			$(".title").text(data.title);
			htmlStr = template("mainTemplate", data);
			dataCount =  data.main.length;
			$(".dataCount").text(dataCount);
			$("#data-content").html(htmlStr);
			var htmls = [];
			for(var i=0;i<data.main.length;i++){
				htmls.push(data.main[i].content);
			}
			$(".message").each(function(index){
				$(this).find(".mc").html(htmls[index]);
			});
			$(".pTime").each(function(){
					var text = formatDate($(this).text());
					$(this).text(text);
				})
			totalHeight = $("#data-content")[0].scrollHeight;
		});
		
	});

	$(".userInfo").click(function(){
//		console.log($.cookie("wcID"));
		if($.cookie("wcID")){
			location.href = "userInfo.html";
		}else{
			if(confirm("您尚未登陆是否跳转到登陆页面?")){
				location.href = "/register2";
			}	
		}
	})
	
	$(".posting").click(function(){
		if($.cookie("wcID")){
			location.href = "/post.html";
		}else{
			if(confirm("您尚未登陆是否跳转到登陆页面?")){
				location.href = "/register2";
			}	
		}
	});

	//function sendFCs(){	
	//	$(".likeWC").each(function(){
	//		if($(this).data("favaCount")){
	//			var sId= $(this).parents("li").find(".sectionID").text();
	//			var obj = {sId,favaCount:$(this).data("favaCount")}
	//			favaCounts.push(obj);
	//		}
	//	});
	//	if(favaCounts.length){
	//		$.post("/favaCount",favaCounts);
	//	}
	//}
});
//window.onbeforeunload = function(){
////	alert(1);
//	sendFCs();
//}